var config = require('../base.conf.js').config;
var Api=require('Api.js');
/**
 * @param url//请求url的key
 * @param method//请求方式
 * @param datas//请求所传参数
 * @param header//设置请求头
 */
var Ajax = {
  post: function(url, datas, header) { 
    return this.request(url, "POST", datas, header);
  },
  get: function(url, datas, header) {
    return this.request(url, "GET", datas, header);
  },
  getApi: function (url) {
    if (Api[url]) {
      // return (config.isDebug ? config.devUrl : config.prodUrl) + Api[url];
      var serviceType = Api[url].service
      return (config.isDebug ? config[serviceType].devUrl : config[serviceType].prodUrl) + Api[url].url;
    }else{
      return null;
    }
  },
  getHeader: function () {
    return {
      "content-type": "application/x-www-form-urlencoded",
    }
  },
  getData: function (datas) {
    return datas;
  },
  request: function(api,method, datas, header) {
    var self=this;
    return new Promise((reselove, reject) => {
      if (!Api[api]) {
        console.error("api is undefined!!!")
        reject("api is undefined!!!");
        return;
      }
      wx.request({
        url: self.getApi(api),
        data: self.getData(datas) || {},
        method: method,
        header: Object.assign(self.getHeader(), header || {}),
        success: function(rdata) {
          if (rdata.statusCode) {
            reselove(rdata.data);
          } else {
            reject(rdata);
          }
        },
        fail: function(e) {
          reject(e);
        }
      })
    });
  }
}
module.exports = Ajax;